package com.nvn.androidapp.fragments;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nvn.androidapp.R;
import com.nvn.androidapp.ViewPagerActivity;
import com.nvn.androidapp.Objects.Picture;
import com.nvn.androidapp.utils.Statics;

public class ViewImageFragment extends Fragment{
	private View v;
	private ImageView imgSource, redSquare, imv_replace, imv_delete, imv_shuffle;
	private EditText edt_caption;
	private RelativeLayout parent_view;
	private Bitmap bitmap;
	private boolean first = true;
	private Picture pic;
	private int left = -1, top = -1, right = -1, bottom = -1, rule1=-999, rule2;
	private ImageLoader imageLoader;
	private DisplayImageOptions options;
//	private boolean isGetThumb = false;
	private FragmentActivity parent;
	
	
	public static ViewImageFragment newInstance(Picture pic, ImageLoader imageLoader, DisplayImageOptions options) {
		ViewImageFragment fragment = new ViewImageFragment();
		fragment.pic = pic;
		fragment.imageLoader = imageLoader;
		fragment.options = options;
        return fragment;
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		v = inflater.inflate(R.layout.layout_view_image, container, false);
		
		parent = getActivity();
		
		parent_view = (RelativeLayout)v.findViewById(R.id.parent_view);
		imgSource = (ImageView) v.findViewById(R.id.imv_viewimg);
		
		redSquare = (ImageView)v.findViewById(R.id.red_square);
		
//		if(isGetThumb){
//			redSquare.setVisibility(View.VISIBLE);
			if(pic.getID() !=-1 && pic.getRule1() != -999){
				left = pic.getLeft();
				top = pic.getTop();
				bottom = pic.getBot();
				right = pic.getRight();
				rule1 = pic.getRule1();
				rule2 = pic.getRule2();
				updateRedSquare();
			}else{
				RelativeLayout.LayoutParams lp = new LayoutParams(Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS), Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS)); 
				lp.addRule(RelativeLayout.CENTER_IN_PARENT);
				redSquare.setLayoutParams(lp);
			}
//		}else{
//			redSquare.setVisibility(View.GONE);
//		}
		
		edt_caption = (EditText)v.findViewById(R.id.edt_caption);
		
		
		
		/*imgSource.setImageResource(R.drawable.ic_no_image);
		bitmap = Statics.loadResizedBitmap(pic.getPath(), imgSource.getWidth(), imgSource.getHeight(), true);
		imgSource.setImageBitmap(bitmap);
		if(isGetThumb){
			if(left != -1){
				updateRedSquare();
			}
			imgSource.setOnTouchListener(imgSourceOnTouchListener);
		}*/
		
		
		imageLoader.displayImage("file://"+pic.getPath(), imgSource, options, new ImageLoadingListener() {
			
			@Override
			public void onLoadingStarted(String imageUri, View view) {}
			
			@Override
			public void onLoadingFailed(String imageUri, View view,
					FailReason failReason) {}
			
			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//				if(!isGetThumb){
//					imgSource.setImageBitmap(loadedImage);
//					return;
//				}
				
				if(imgSource.getWidth()!=0 && imgSource.getHeight()!=0) {
					if(null != bitmap) bitmap.recycle();
					bitmap = Bitmap.createScaledBitmap(loadedImage, imgSource.getWidth(), imgSource.getHeight(), true);
				}
				
				imgSource.setImageBitmap(bitmap);
				
				if(left != -1){
					updateRedSquare();
				}
				imgSource.setOnTouchListener(imgSourceOnTouchListener);
			}
			
			@Override
			public void onLoadingCancelled(String imageUri, View view) {}
		});
		
		if(null != pic.getCaption()){
			edt_caption.setText(pic.getCaption());
		}
		
		
		
		imv_replace = (ImageView)v.findViewById(R.id.imv_replace);
		imv_delete = (ImageView)v.findViewById(R.id.imv_delete);
		imv_shuffle = (ImageView)v.findViewById(R.id.imv_shuffle);
		
		imv_replace.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ViewPagerActivity act = (ViewPagerActivity)parent;
				act.onReplacePicture(ViewImageFragment.this, pic);
			}
		});
		
		imv_delete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(parent)
				.setTitle("Notice")
				.setMessage("Are you sure want to delete this item?")
				.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						ViewPagerActivity act = (ViewPagerActivity)parent;
						act.onDeletePicture(ViewImageFragment.this, pic);
					}
				})
				.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {}
				})
				.show();
			}
		});
		
		imv_shuffle.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ViewPagerActivity act = (ViewPagerActivity)parent;
				act.onShufflePicture(ViewImageFragment.this, pic);
			}
		});
		
		return v;
	}
	
	private OnTouchListener imgSourceOnTouchListener= new OnTouchListener(){

		@Override
		public boolean onTouch(View view, MotionEvent event) {
			first = false;
			float eventX = event.getX();
			float eventY = event.getY();
			
			updatePosition(eventX, eventY);
			
			return true;
		}
	};
	
	public void updateImage(String path){
		
		imageLoader.displayImage("file://"+path, imgSource, options, new ImageLoadingListener() {
			
			@Override
			public void onLoadingStarted(String imageUri, View view) {}
			
			@Override
			public void onLoadingFailed(String imageUri, View view,
					FailReason failReason) {}
			
			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { 
//				if(!isGetThumb){
//					imgSource.setImageBitmap(loadedImage);
//					return;
//				}
				if(null != bitmap) bitmap.recycle();
				bitmap = Bitmap.createScaledBitmap(loadedImage, imgSource.getWidth(), imgSource.getHeight(), true);
				imgSource.setImageBitmap(bitmap);
				imgSource.setOnTouchListener(imgSourceOnTouchListener);
			}
			
			@Override
			public void onLoadingCancelled(String imageUri, View view) {}
		});
	}
	
	private void updateRedSquare(){
        RelativeLayout.LayoutParams lp = new LayoutParams(Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS), Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS)); 
        redSquare.setLayoutParams(lp);
        lp.addRule(rule1, RelativeLayout.TRUE);
        lp.addRule(rule2, RelativeLayout.TRUE);
        lp.leftMargin = left;
        lp.topMargin = top;
        lp.rightMargin = right;
        lp.bottomMargin = bottom;
        redSquare.setLayoutParams(lp);
	}
	
	private void updatePosition(float x0, float y0) {
		float[] eventXY = new float[] {x0, y0};

		setBitmapPosition((int)x0, (int)y0);
		
		Matrix invertMatrix = new Matrix();
		imgSource.getImageMatrix().invert(invertMatrix);
		invertMatrix.mapPoints(eventXY);
		
		int x = Integer.valueOf((int)eventXY[0]);
		int y = Integer.valueOf((int)eventXY[1]);
		
//		Toast.makeText(this, text, duration)
		
		
		//Limit x, y range within bitmap
		if(x < 0 || x > bitmap.getWidth()-1 || y < 0 || y > bitmap.getHeight()-1) return;
		
		
		
	}
	
	public void setBitmapPosition(int x, int y) {
		ImageView iv = redSquare;
		
        RelativeLayout rl = (RelativeLayout) iv.getParent();

        // get bitmap size
        int imgDx = iv.getLayoutParams().width;
        int imgDy = iv.getLayoutParams().height;
        // get container size
        int dx = rl.getWidth();
        int dy = rl.getHeight();

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                imgDx, imgDy);
        iv.setLayoutParams(lp);

//        x += (dx-bitmap.getWidth())/2;
//        y += (dy-bitmap.getHeight())/2;
        
        if(x<= imgDx/2) x= imgDx/2;
        if(y <= imgDy/2) y = imgDy/2;
        if(x >= (dx-imgDx/2)) x = (dx-imgDx/2);
        if(y >= (dy-imgDy/2)) y = (dy-imgDy/2);
       
        if (x <= (dx / 2)) {
            // i'm on the left side of the view so let's align to left
            lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
            rule1 = RelativeLayout.ALIGN_PARENT_LEFT;
            lp.leftMargin = x - imgDx / 2;
        } else {
            // align to right. we are past the middle
            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
            rule1 = RelativeLayout.ALIGN_PARENT_RIGHT;
            lp.rightMargin = dx - (x + imgDx / 2);
        }

        if (y <= (dy / 2)) {
            // align to top
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
            rule2 = RelativeLayout.ALIGN_PARENT_TOP;
            lp.topMargin = y - imgDy / 2;

        } else {
            // align to bottom
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            rule2 = RelativeLayout.ALIGN_PARENT_BOTTOM;
            lp.bottomMargin = dy - (y + imgDy / 2);
        }
        left = lp.leftMargin;
        top = lp.topMargin;
        right = lp.rightMargin;
        bottom = lp.bottomMargin;
        iv.setLayoutParams(lp);
    }
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if ((savedInstanceState != null) && savedInstanceState.containsKey("LEFT")) {
        	left = savedInstanceState.getInt("LEFT");
        	top = savedInstanceState.getInt("TOP");
        	right = savedInstanceState.getInt("RIGHT");
        	bottom = savedInstanceState.getInt("BOTTOM");
        	rule1 = savedInstanceState.getInt("RULE1");
        	rule2 = savedInstanceState.getInt("RULE2");
        }
    }
	
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("LEFT", left);
        outState.putInt("TOP", top);
        outState.putInt("RIGHT", right);
        outState.putInt("BOTTOM", bottom);
        outState.putInt("RULE1", rule1);
        outState.putInt("RULE2", rule2);
    }
	
	public Bitmap getThumnail(){
		
		int	x = (parent_view.getWidth()-Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS))/2;
		int y = (parent_view.getHeight()-Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS))/2;
		
		if(rule1 != -999){
			if(rule1 == RelativeLayout.ALIGN_PARENT_LEFT){
				x=left;
			}else{
				x=parent_view.getWidth()-right-Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS);
			}
			if(rule2 == RelativeLayout.ALIGN_PARENT_TOP){
				y=top;
			}else{
				y=parent_view.getHeight()-bottom-Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS);
			}
		}
		if(null == bitmap) return null;
		
		return Bitmap.createBitmap(bitmap, 
									x, 
									y, 
									Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS), 
									Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS));

	}

	/**
	 * @param isGetThumb the isGetThumb to set
	 */
	/*public void setGetThumb(boolean isGetThumb) {
		this.isGetThumb = isGetThumb;
		if(isGetThumb && null != v && null != redSquare){ // TRUE
			redSquare.setVisibility(View.VISIBLE);
			RelativeLayout.LayoutParams lp = new LayoutParams(Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS), Statics.PixelFromDp(parent, Statics.SQUARE_MATRICS)); 
			lp.addRule(RelativeLayout.CENTER_IN_PARENT);
			redSquare.setLayoutParams(lp);
			updateImage(pic.getPath());
		}else if(!isGetThumb && null != v && null != redSquare){ // FALSE
			redSquare.setVisibility(View.GONE);
			imgSource.setOnTouchListener(null);
		}
	}*/
	/**
	 * @return the isGetThumb
	 */
	/*public boolean isGetThumb() {
		return isGetThumb;
	}*/

	public Picture saveData(){
		String caption = "";
		try{
			caption = edt_caption.getText().toString().trim();
		}catch(Exception e){}
		pic.setCaption(caption);
		pic.setLeft(left);
		pic.setTop(top);
		pic.setRight(right);
		pic.setBot(bottom);
		pic.setRule1(rule1);
		pic.setRule2(rule2);
		return pic;
	}
}
